目前已經將新增和取得文章的API完成,接著我們要來開發修改和刪除文章的API
在posts-controller.js
下新增updatePost的邏輯
exports.updatePost = async (req, res, next) => {
try {
const { postId } = req.params;
if (!postId) {
return next(new HttpError("PostId is required", 400));
}
const { title, tags, content, coverImage, authorId } = req.body;
// 檢查文章是否存在
const post = await Post.findById(postId);
if (!post) {
return next(new HttpError("Post not found", 404));
}
// 更新文章資料
if (title && title.trim() !== "") {
post.title = title;
}
if (tags && Array.isArray(tags) && tags.length !== 0) {
post.tags = tags;
}
if (content && content.trim() !== "") {
post.content = content;
}
if (coverImage) {
post.coverImage = coverImage;
}
await post.save();
res.status(200).json(post);
} catch (error) {
console.log(error);
next(new HttpError("Server error", 500));
}
}
exports.getPost = getPost;
exports.createPost = createPost;
exports.updatePost = updatePost;
我們先前已經有在post-routes.js
新增更新文章的route,將剛剛建立的controller
引入就完成了
//post-routes.js
const express = require('express');
const router = express.Router();
const postController = require('../controllers/posts-controller');
...(略)
//@router PUT /api/posts/:postId
//@desc 更新文章
//@access Public
router.put("/:postId", postController.updatePost);
module.exports = router;
更新前
更新後
一樣在posts-controller.js
下新增deletePost的邏輯
//posts-controller.js
//前面都是用const宣告mockpost,因為刪除會改變裡面的內容,所以需要改為let才能正常執行刪除。
let MOCK_POSTS = [
{
id: 'p1',
title: '文章1',
tags: ['frontend'],
content:'ChatGPT'
},
{
id: 'p2',
title: '文章2',
tags: ['lifeStyle'],
content:'Micro frontend'
}
]
...(略)
const deletePost = (req,res,next)=>{
const postId = req.params.postId;
const postIndex = MOCK_POSTS.findIndex(post => post.id === postId);
if(postIndex < 0){
return next(new HttpError('刪除失敗:此id的文章不存在', 404));
}
MOCK_POSTS.filter(post => post.id !== postId);
res.status(201).json({message: '刪除成功'});
}
exports.getPost = getPost;
exports.createPost = createPost;
exports.updatePost = updatePost;
exports.deletePost = deletePost;
接著在post-routes.js
引入剛剛建立的controller
//post-routes.js
const express = require('express');
const router = express.Router();
const postController = require('../controllers/posts-controller');
...(略)
//@router DELETE api/posts
//@desc 刪除文章
//@access Public*/
router.delete("/:postId", postController.deletePost);
module.exports = router;